import {
  Canvas,
  useFrame,
  useThree,
  type Vector3 as vector3,
} from "@react-three/fiber";
import React, { useEffect, useState, useRef } from "react";
import { Vector3, Group, Object3DEventMap } from "three";
import * as Three from "three";
import gsap from "gsap";
interface data {
  length: number;
  Vector3s: vector3[];
}
const radius = 15; //每个旋转角度15度
const startLength = 50; //初始长度
const endLength = 300; //结束长度
const init = () => {
  let data: data[] = [];
  //遍历圈数
  for (let i = startLength; i <= endLength; i += 10) {
    const vector3s: vector3[] = [];
    //遍历角度
    for (let j = 0; j < 360; j += radius) {
      const rad = (j * Math.PI) / 180;
      vector3s.push(new Vector3(i * Math.cos(rad), 0, i * Math.sin(rad)));
    }
    data.push({
      length: i,
      Vector3s: vector3s,
    });
  }
  return data;
};
const getRadius = (radius: number) => {
  const rad = radius % 360;
  return rad ? rad : 360;
};
const CustomGroup = ({
  children,
  position,
}: {
  children: any;
  position: vector3;
}) => {
  const GroupRef = useRef<Group>(null);
  useEffect(() => {}, []);
  return (
    <group position={position} ref={GroupRef}>
      {children}
    </group>
  );
};
let time = 0;
export function Lizi() {
  const [state, setState] = useState<data[]>(init());
  const [currentGroup, setCurrentGroup] = useState<number>(state[0].length);
  const animate = () => {
    setCurrentGroup((prev) => {
      if (prev >= state[state.length - 1].length) {
        return state[0].length;
      } else {
        return prev + 10;
      }
    });
  };
  useFrame((state, delta) => {
    if (new Date().getTime() - time > 100) {
      time = new Date().getTime();
      animate();
    }
  });
  useEffect(() => {
    console.log(currentGroup);
  }, [currentGroup]);

  return (
    <>
      {state.map((item, index) => (
        <CustomGroup key={index} position={new Three.Vector3(1, 1, 2)}>
          {item.Vector3s.map((itemm, indexx) => (
            <mesh
              key={indexx}
              position={itemm}
              material={
                item.length == currentGroup
                  ? new Three.MeshBasicMaterial({
                      color: new Three.Color("green"),
                    })
                  : new Three.MeshBasicMaterial({
                      color: new Three.Color("red"),
                    })
              }
            >
              <boxGeometry args={[2, 2, 2]} />
            </mesh>
          ))}
        </CustomGroup>
      ))}
    </>
  );
}
